#include <iostream>
#include <ctime>
#include "Socket.hpp"
#include "Protocol.hpp"
using namespace socket_ns;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage:" << argv[0] << " server-ip server_port" << std::endl;
        exit(0);
    }
        std::string serverip = argv[1];
        uint16_t serverport = std::stoi(argv[2]);
        SockSPtr sock = std::make_shared<TcpSocket>();
        if (!sock->BuidClientSocket(serverip, serverport))
        {
            std::cerr << "connect error" << std::endl;
            exit(1);
        }
        srand(time(nullptr) ^ getpid());
        const std::string opers = "+*/%&^!";
        // 构建数据
        std::string message;
        while (true)
        {
            int x = rand() % 10;
            usleep(x * 1000);
            int y = rand() % 10;
            usleep(x * y * 1000);
            char oper = opers[y % opers.size()];
            // 序列化(成string)
            auto req = Factory::BuildRequestDefault();
            req->SetValue(x, y, oper);
            std::cout<<x<<y<<oper<<std::endl;
            // 成string
            std::string jsonstr;
            req->Serialize(&jsonstr);
             std::cout<<jsonstr<<std::endl;
            // 在字符串上加上一些信息属性
            std::string reqstr = Encode(jsonstr);
            std::cout<<"request string : \n"<<reqstr<<std::endl;
            // 发送信息
            sock->Send(reqstr);
            // 读取应答，respsonse
            while(true)
            {
            ssize_t n = sock->Recv(&message);
             
            if (n <= 0)
            {  
                break;
            }
            std::string package = Decode(message);
            if (package.empty())
                continue;   
             std::cout << "package: \n" << package << std::endl;
            auto resp=Factory::BuildResponseDefault();
            resp->Deserialize(message);
        
            resp->Print();
             break;
            }

       
    
        }
         sock->close();
        return 0;
}